package com.example.lzy.viewpagerandfragment;

import android.Manifest;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.lzy.photo.FileHelper;
import com.example.lzy.photo.PerMissionContants;
import com.example.lzy.photo.SelectPicPopup;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.util.List;


public class Main3Activity extends AppCompatActivity {
    private ImageView imageV;
    private Uri imageUrl;//照片地址uri对象
    private int destType = FileHelper.JPEG;
    private static final int REQUEST_CODE_TAKE_PIC_CAMERA = 100;//拍照请求码

    private static final int REQUEST_CODE_CHOOSE = 233;//图库选取照片请求码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        initView();
    }

    private void initView() {
        imageV= (ImageView) findViewById(R.id.image);
        findViewById(R.id.select_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final SelectPicPopup popup=new SelectPicPopup(getApplicationContext());
                popup.showPopup(findViewById(R.id.activity_main3));
                popup.setOnBtnClick(new SelectPicPopup.OnBtnClickListener() {
                    @Override
                    public void getFlag(int flag) {
                        if (flag==1){//相册
                            popup.dismiss();
                            selectPicFromGallery();
                        }else if (flag==0){//拍照
                            popup.dismiss();
                            if (hasPermission(PerMissionContants.HARDWEAR_CAMERA_PERMISSION)){
                                openCamera();
                            }else {

                                requestPermission(PerMissionContants.HARDWEAR_CAMERA_CODE,PerMissionContants.HARDWEAR_CAMERA_PERMISSION);
                                Toast.makeText(getApplicationContext(),"权限:"+hasPermission(PerMissionContants.HARDWEAR_CAMERA_PERMISSION),Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                });
            }
        });
    }

    /**
     * 打开相册进行拍照
     */
    private void openCamera() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //创建一个临时文件夹存储拍摄的照片
        File file = FileHelper.createFileByType(getApplicationContext(), destType, System.currentTimeMillis()+"");
        imageUrl=Uri.fromFile(file);//解析出uri对象
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//版本过高的拍照路径
            Log.e("进入1","进入1");
            file = new File(getApplicationContext().getCacheDir(), System.currentTimeMillis()+".jpg");
            imageUrl = Uri.fromFile(file);

            Toast.makeText(getApplicationContext(), "TODO", Toast.LENGTH_SHORT).show();
            // 将文件转换成content://Uri的形式
            Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".provider", file);
            // 申请临时访问权限
            takePictureIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);

        } else {
            Log.e("进入2","进入2");
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUrl);
        }


        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            Log.e("进入3","进入3");
            startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PIC_CAMERA);
        }
    }

    /**
     * 打开相册选取照片
     */
    private void selectPicFromGallery() {
        Matisse.from(Main3Activity.this)
                .choose(MimeType.allOf())
                .countable(true)
                .spanCount(4)
                .maxSelectable(1)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(REQUEST_CODE_CHOOSE);
    }

    /**
     * 发起权限请求
     */
    private void requestPermission(int code,String...permissions){
        if (Build.VERSION.SDK_INT>=23){//判断是否大于6.0版本(当前手机的安卓系统是否是6.0或以上)
            requestPermissions(permissions,code);
        }
    }

    /**
     * 校验权限是否通过(安卓6.0以上的动态权限需要调用该方法)
     * @param permissions
     * @return
     */
    private boolean hasPermission(String...permissions){
        for (String permission:permissions) {
            if (ContextCompat.checkSelfPermission(getApplicationContext(),permission)!= PackageManager.PERMISSION_GRANTED){
                return false;
            }
        }
        return true;
    }

    /**
     * 权限请求回调结果处理
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode== PerMissionContants.HARDWEAR_CAMERA_CODE){//拍照权限
            if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                Toast.makeText(getApplicationContext(),"权限请求结果",Toast.LENGTH_SHORT).show();
                openCamera();
            }

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==REQUEST_CODE_TAKE_PIC_CAMERA&&resultCode==RESULT_OK){//拍照请求回调成功
            if (imageUrl!=null){
                //根据uri获取图片的真实路径
                String path=getRealFilePath(getApplicationContext(),imageUrl);
                Bitmap bitmap=BitmapFactory.decodeFile(path);//根据图片的路径字符串解析成bitmap
                imageV.setImageBitmap(bitmap);
            }
        }else if (requestCode==REQUEST_CODE_CHOOSE&&resultCode==RESULT_OK){
            List<Uri> uriList=Matisse.obtainResult(data);
            if (uriList.size()==1){
                String path=getRealFilePath(getApplicationContext(),uriList.get(0));
                Bitmap bitmap=BitmapFactory.decodeFile(path);//根据图片的路径字符串解析成bitmap
                imageV.setImageBitmap(bitmap);
            }
        }
    }

    /**
     * 该方法根据图片uri得出其真实路径
     * @param context 上下文
     * @param uri 图片对应的uri对象
     * @return 图片的真实路径字符串
     */
    public String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
}

